// JavaScript Document
$(document).ready(function() {
  $('#edit-assessment-search-active').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-assessment-search-expire').datepicker({
    dateFormat:'mm-dd-yy'
  });
});

//Function to apply filter action and reload the listing
function applyAction(pageno, action){
  //prepare the field values for filtering
  var search_assessment = $.trim($("#edit-assessment-search-details").val());
  var search_active = $("#edit-assessment-search-active").val();
  var search_expire = $.trim($("#edit-assessment-search-expire").val());
  var search_status = $.trim($("#edit-assessment-search-status").val());
  var sort = $('#hid_sort').val();
  $('#hid_pageno').val(pageno);
  //check for search criteria and return false if no value
  if (search_assessment == "" && search_active == "" && search_expire == "" && search_status == "") {
    openAlertDialog(300, 125, 'Information', 'Please enter the search criteria');
    return;
  }
	
  //pagination loading animation
  pagination_loading("page");
	
  $.ajax({
    type : "POST",
    url : baseurl+"assessment/actions/filter",
    data : "search_assessment="+ encodeURIComponent(search_assessment) +"&search_active="+search_active+"&search_expire="+search_expire+"&search_status="+search_status+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
    async : true,
    cache : false,
    success : function (msg) {
      //replace the div with the new content loaded
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();
			
      var str="";
      var to = page*limit;
      //create the pagination links
      str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
      if (page > 1) {
        str += '<a href="javascript:void(0)" onclick = "applyAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
      }
      if (to < counter) {
        str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyAction('+(page+1)+',\''+action+'\')" class="red">Next >></a>';
      }

      //No records found when no result
      if (counter <= 0) {
        str = '';
      }
			
      //reload the content of the pagination links
      $("#pagingdivtop").html(str);
      $("#pagingdivbottom").html(str);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to close the dialog box
function closeDialog(testId){
  $('#dialog').dialog('destroy');
}

//Function to open dialog window for creating assessment
function createAssessment(){
  openDialog("createassessment", 0, 600, 335, "Create Assessment");
}

//Function to open dialog window for editing assessment
function editAssessment(id){
  reopen_dialog(600, 335,$('#assessment_title').html());
  editAssessmentDialog(id);
}

//Function to open dialog window for editing questions for assessment
function editAssessmentQuestion(assessid){
  reopen_dialog(850,500, "Add Question");
  editAssessmentQuestionDialog(assessid);
}

//Function to open dialog window for preview question
function previewAssessmentQuestion(id){
  reopen_dialog(700,515,"Preview Question");
  previewAssessmentQuestionsDialog(id);
}

//Function to save assessment questions
function saveAssessmentQuestions(assessId, action, qid){
  var type = $('#edit-question-type').val();
  var question = editor.getData();
  var refusestr = question.substring(question.length-7);
  if($.trim(refusestr)=="<br />"){
    question = question.substring(0,question.length-7);
  }
  var disp_order = $('#edit-question-displayorder').val();
  if(!disp_order || disp_order==0 || disp_order=="")
    disp_order = 1;
  var ismandatory = $('#edit-question-mandatory').is(':checked');
	
  //code to validate the fields
  var lines = 10;
  var str = "";
  if(type == "") {
    str += "Please select the question type";
    lines+=18;
  }
  if($.trim(question) == "" || $.trim(question) == "<br />") {
    if(str!="")
      str+= "<br/>";
    str += "Please add a question";
    lines+=18;
  }
  if(type != "" && type != "Textbox" && type != "Textarea" && answers.length==0) {
    if(str!="")
      str+= "<br/>";
    str += "Please add the answers for this question";
    lines+=18;
  }
  if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
    var k=0;
    for(var i=0; i<answers.length; i++){
      if(answers[i][3] == 'true'){
        k++;
      }
    }
    if(k > 1){
      if(str!="")
        str+= "<br/>";
      str += "Please select only one default value";
      lines+=18;
    }
  }

  if (str != "") {
    resize_dialog(850,500+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
	
  if(type == "Radio button"){
    type = "Radiobutton";
  }
  else if(type=="Checkbox"){
    type = "Checkbox";
  }
  else if(type=="Dropdown List"){
    type = "Dropdown";
  }
  else if(type=="Multiselect List"){
    type = "Multiselect";
  }
  else if(type=="Textbox"){
    type = "Textbox";
  }
  else if(type=="Textarea"){
    type = "Textarea";
  }
  else if(type=="Filtered List"){
    type = "Filtered List";
  }
  else if(type=="Multiselect Filtered List"){
    type = "Multiselect Filtered List";
  }
	else if(type=="Source-Target List"){
    type = "Source-Target List";
  }
	
  get_answers();
	
  var ans_str = "";
  for(var i=0; i<answers.length; i++){
    if(ans_str!="")
      ans_str+="*#~*";
    ans_str += answers[i][0]+","+answers[i][1]+","+answers[i][2]+","+(answers[i][3]==''||answers[i][3]=='false'?'false':'true');
  }
  //Page loading animation
  $('#dialog').html('<div style="padding-top:175px; padding-left:350px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
	
  //AJAX callback to create/edit questions
  $.ajax({
    type : "POST",
    url : baseurl+"assessment/edit_action/question"+((action=="edit"||action=="edit_add")?"/"+qid:""),
    data: "assessId="+assessId+"&qtype="+type+"&question="+encodeURIComponent(question)+"&answers="+encodeURIComponent(ans_str)+"&ismandatory="+ismandatory+"&disp_order="+disp_order,
    async : true,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      //Process if the service return success message
      if(json.Message=="Success"){
        answers = new Array();
        if (action=="add" || action=="edit_add") {
          reopen_dialog(850,500,"Add Question");
          editAssessmentQuestionDialog(assessId);
        }
        else {
          reopen_dialog(700,515,"Preview Question");
          previewAssessmentQuestionsDialog(assessId);
        }
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to convert to date string format
function convertDateString (date) {
  var split_date = date.split("-");
  var date_string = split_date[2] +"/"+ split_date[0] +"/"+ split_date[1];
  return date_string;
}

//Function to save assessment details for creating
function submitAssessment(){
  var title = $('#edit-assessment-title').val();
  var desc = $('#edit-assessment-description').val();
  //var desc = editor.getData();
  var actDate = $.trim($('#edit-assessment-actdate').val());
  var expDate = $.trim($('#edit-assessment-expdate').val());
  var status = $('#edit-assessment-status').val();
  var siteid = $('#edit-assessment-site').val();
	
  //code to validate the fields
  var lines = 10;
  var str = "";
  if($.trim(title) == ""){
    str += "Title should not be empty";
    lines+=18;
  }
  if($.trim(title) != ""){
    if($.trim(title).length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Title should not be more than 50 characters";
      lines+=18;
    }
  }
  if($.trim(desc) != ""){
    if($.trim(desc).length > 1000){
      if(str!="")
        str+= "<br/>";
      str += "Description should not be more than 1000 characters";
      lines+=18;
    }
  }
  if($.trim(actDate)==""){
    if(str!="")
      str+= "<br/>";
    str += "Activation date should not be empty";
    lines+=18;
  }
  if ($.trim(expDate) != "") {
	  /*
    var actdate_str = convertDateString(actDate);
    var expdate_str = convertDateString(expDate);
    if (!fromGreaterThanTo(actdate_str, expdate_str)) {
      if(str!="")
        str+= "<br/>";
      str += "Expiration date should be greater than the Activation date";
      lines+=18;
    }
*/

    var actObj = new Date(actDate.replace(/-/g,"/"))
    var expObj = new Date(expDate.replace(/-/g,"/"))
    if (actObj > expObj) {
      if(str!="")
        str+= "<br/>";
      str += "Expiration date should be greater than the Activation date";
      lines+=18;
    }
  }

  var actdate = actDate.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(expDate!=''){
	  var expdate = expDate.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }
  if(status==0){
    if(str!="")
      str+= "<br/>";
    str += "Select any status";
    lines+=18;
  }
  if(siteid <= 0){
    if(str!="")
      str+= "<br/>";
    str += "Select any site to associate with this assessment";
    lines+=18;
  }
	
  if (str != "") {
    resize_dialog(600, 335+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }

  var content = $('#dialog').html();
  //Page loading animation
  $('#dialog').html('<div style="padding-top:80px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');	
	
  //AJAX callback to create an assessment
  $.ajax({
    type : "POST",
    url : baseurl+"assessment/create",
    data: "title="+encodeURIComponent(title)+"&desc="+encodeURIComponent(desc)+"&actDate="+actDate+"&expDate="+expDate+"&status="+status+"&siteid="+siteid,
    async : true,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      //Process if the service return success message
      if(json.Message=="Success"){
        applyAction(1, $('#edit-apply').attr('actionitem'));
        reopen_dialog(850,500,"Add Question");
        editAssessmentQuestionDialog(json.evaluationId);
      }
      else{
        if(json.Error=="exist"){
          $.get(baseurl+'assessment/edit/0', function callback(res){
            $('#dialog').html(res);
            createDatePicker('edit-assessment-expdate',0);
            createDatePicker('edit-assessment-actdate',0)

            $('#dialog').html(content);
            $('#edit-assessment-title').val(title);
            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-actdate').val(actDate);
            $('#edit-assessment-expdate').val(expDate);
            $('#edit-assessment-status').val(status);
            $('#edit-assessment-site').val(siteid);
            resize_dialog(600, 335+30);
            styleStatusMessages("Assessment title already exists", "statusMessage", "failure");
          });
          resize_dialog(600, 335+30);
        }else{
          $.get(baseurl+'assessment/edit/0', function callback(res){
            $('#dialog').html(res);
            createDatePicker('edit-assessment-expdate',0);
            createDatePicker('edit-assessment-actdate',0)

            $('#dialog').html(content);
            $('#edit-assessment-title').val(title);
            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-actdate').val(actDate);
            $('#edit-assessment-expdate').val(expDate);
            $('#edit-assessment-status').val(status);
            $('#edit-assessment-site').val(siteid);
            resize_dialog(600, 335+30);
            styleStatusMessages("Failure to save assessment", "statusMessage", "failure");
          });
          resize_dialog(600, 335+30);
        }				
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save assessment details for editing
function editSave(id){
  var title = $('#edit-assessment-title').val();
  var desc = $('#edit-assessment-description').val();
  //var desc = editor.getData();
  var actDate = $('#edit-assessment-actdate').val();
  var expDate = $('#edit-assessment-expdate').val();
  var status = $('#edit-assessment-status').val();
  var siteid = $('#edit-assessment-site').val();
	
  //code to validate the fields
  var lines = 10;
  var str = "";
  if($.trim(title) == ""){
    str += "Title should not be empty";
    lines+=18;
  }
  if($.trim(title) != ""){
    if($.trim(title).length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Title should not be more than 50 characters";
      lines+=18;
    }
  }
  if($.trim(desc) != ""){
    if($.trim(desc).length > 1000){
      if(str!="")
        str+= "<br/>";
      str += "Description should not be more than 1000 characters";
      lines+=18;
    }
  }
  if($.trim(actDate)==""){
    if(str!="")
      str+= "<br/>";
    str += "Activation date should not be empty";
    lines+=18;
  }
  if ($.trim(expDate) != "") {

    var actObj = new Date(actDate.replace(/-/g,"/"))
    var expObj = new Date(expDate.replace(/-/g,"/"))

    if (actObj > expObj) {
      if(str!="")
        str+= "<br/>";
      str += "Expiration date should be greater than the Activation date";
      lines+=18;
    }
  }


  var actdate = actDate.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(expDate!=''){
	  var expdate = expDate.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }

  if(status==0){
    if(str!="")
      str+= "<br/>";
    str += "Select any status";
    lines+=18;
  }
	
  if (str != "") {
    resize_dialog(600, 335+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }

  //set the url for AJAX call and the mode
  var mode = "edit";
  var url = "assessment/edit_action/"+id;
  if($('#ui-dialog-title-dialog').html()=="Clone Assessment"){
    url = "assessment/clone/save/"+id;
    mode = "clone";
  }
  //Page loading animation
  $('#dialog').html('<div style="padding-top:80px; padding-left:250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');	

  $.ajax({
    type : "POST",
    url : baseurl + url,
    data: "title="+encodeURIComponent(title)+"&desc="+encodeURIComponent(desc)+"&actDate="+actDate+"&expDate="+expDate+"&status="+status+(mode=="clone"?"&siteid="+siteid:""),
    async : true,
    cache : false,
    success : function (msg) {
      var url = 'assessment/edit/'+id;
      var height = 0;
      if(mode == "clone"){
        url = 'assessment/clone/'+id;
        height = 25;
      }
      eval("var json="+msg);
      if(json.Message=="Success"){
        $('#dialog').dialog('destroy');
        applyAction(1,$('#edit-apply').attr('actionitem'));
      }
      else{
        if(json.Error=="exist"){
          $.get(baseurl+url, function callback(res){
            $('#dialog').html(res);
            createDatePicker('edit-survey-actdate',0);
            createDatePicker('edit-survey-expdate',0);

            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-title').val(title);
            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-actdate').val(actDate);
            $('#edit-assessment-expdate').val(expDate);
            $('#edit-assessment-status').val(status);
            if(mode=="clone"){
              $('#edit-assessment-site').val(siteid);
            }
            styleStatusMessages("Assessment title already exists", "statusMessage", "failure");
          });
          resize_dialog(600, 335+height);
        }
        else{
          $.get(baseurl+url, function callback(res){
            $('#dialog').html(res);
            createDatePicker('edit-survey-actdate',0);
            createDatePicker('edit-survey-expdate',0);

            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-title').val(title);
            $('#edit-assessment-description').val(desc);
            $('#edit-assessment-actdate').val(actDate);
            $('#edit-assessment-expdate').val(expDate);
            $('#edit-assessment-status').val(status);
            if(mode=="clone"){
              $('#edit-assessment-site').val(siteid);
            }
            styleStatusMessages("Failure to save assessment", "statusMessage", "failure");
          });
          resize_dialog(600, 335+height);
        }
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to set the question type
function setQuestionType(type){
  $('#edit-question-type').val(type);
  $('#edit-question-insert').val(type);
		
  //Hide the answer box if the selected type is a textbox
  if (type == "Textbox" || type == "Textarea") {
    $("#AnswerBox").hide();
  }
  else if (type != "Textbox" && type != "Textarea") {
    $("#AnswerBox").show();
  }
}

//Function to add answers for the questions
var answers = new Array();
function addAnswers(){
  var type = $('#edit-question-type').val();
  //Frame the array by getting the values from the text field
  var ans = $('#edit-question-answer').val();
  var ans_val = $('#edit-question-answer-value').val();
  var ans_def = $('#edit-question-answer-default').val();
	
  //validations for entering answers
  //code to validate the fields
  var lines = 10;
  var str = "";
  if($.trim(ans) == "") {
    str += "Please enter the answer";
    lines+=18;
  }
  if($.trim(ans_val) == "") {
    if(str!=""){
      str+= "<br/>";
    }
    str += "Please enter the answer value";
    lines+=18;
  }
  if(isNaN(ans_val)) {
    if(str!=""){
      str+= "<br/>";
    }
    str += "Please enter only numeric values";
    lines+=18;
  }

	
  if (type != "Checkbox" && type != "Multiselect List" && type != "Multiselect Filtered List" && type != "Source-Target List") {
    if ($("#editAnsDef").val() != "true" || $("#editAnsDef").val() == "") {
      if(ans_def == 'true'){
        var k=0;
        for(var i=0; i<answers.length; i++){
          if(answers[i][3] == 'true'){
            k++;
          }
        }
        if(k>0){
          if(str!="")
            str+= "<br/>";
          str += "Please select only one default value";
          lines+=18;
        }
      }
    }
  }	

  if ($.trim(str)!= "") {
    resize_dialog(850,500+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
	
  $("#statusMessage").hide();
  //update the field based on their positions
  if ($("#editAnsID").val() != 0 && $("#editAnsID").val() != "") {
    answers[$("#editAnsPos").val()] = [ans_val, ans, $("#editAnsID").val(), ans_def];
  }
  else if ($("#editAnsPos").val() != "") {
    answers[$("#editAnsPos").val()] = [ans_val, ans, 0, ans_def];
  }
  else {
    answers.push([ans_val, ans, 0, ans_def]);
  }
  //Display the array of values in UI
  drawAnswers();
	
  //Clear the fields after adding the values
  $('#edit-question-answer').val("");
  $('#edit-question-answer-value').val("");
  $('#edit-question-answer-default').val("false");
  $("#editAnsPos").val("");
  $("#editAnsID").val("");
  $("#editAnsDef").val("");
	
  //rename the button
  $("#edit-answer-add-button").val("Add");
	
  //Focus the answer field after adding the value
  $('#edit-question-answer').focus();
}

//Function to remove the answers
function removeAnswers(pos, ansid){
  openConfirmBox(function(){
    $("#alertdialog").dialog("destroy");
    if(ansid != 0){
      $.ajax({
        type : "POST",
        url : baseurl+"assessment/actions/delete_answer/"+ansid,
        data: "status=&validateFrom=&validateTo=",
        async : true,
        cache : false,
        success : function (msg) {
          if(msg=="Success"){
            answers.splice(pos, 1);
            drawAnswers();
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    }
    else{
      answers.splice(pos, 1);
      drawAnswers();
    }
  },300,100,"Confirm Delete","Do you want to delete this answer?");
}

//Function to edit the answers
function editAnswers(pos, ansid, ans, score, isDefault){
  //store the answerd edited in hidden field
  $("#editAnsPos").val(pos);
  $("#editAnsID").val(ansid);
  $("#editAnsDef").val(isDefault);
	
  //Assign the edited values to the fields
  $("#edit-question-answer").val(ans);
  $("#edit-question-answer-value").val(score);
  $("#edit-question-answer-default").val(isDefault);
	
  //rename the button
  $("#edit-answer-add-button").val("Update");
}

//Function to draw the ansers when edited or deleted or added
function drawAnswers(){
  var str = "";
  str += '<div id="reorder"><ul class="ui-sortable">';
  for(var i=0;i<answers.length;i++){
    str += '<li><div class="'+(i%2==0?"row-dark":"row-light")+'" style="cursor:move;"><input type="hidden" value="'+answers[i][2]+'" /><div class="left-title">'+answers[i][1]+'('+answers[i][0]+')</div><div class="middle-title">'+(answers[i][3]=='true'?'Default':'Non-default')+'</div><div class="right-anstext"><a href="javascript:void(0);" onclick="editAnswers('+i+', '+answers[i][2]+', \''+answers[i][1]+'\', '+answers[i][0]+', \''+((answers[i][3]=='true' || answers[i][3]=='1') ? 'true' : 'false')+'\')">Edit</a>&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);" onclick="removeAnswers('+i+', '+answers[i][2]+')">Delete</a></div><div class="clearit" style="padding:0px;"></div></div></li>';
  }
  str += '</ul></div>';
  $('#answers').html(str);
	
  //make the fields sortable
  $("#reorder ul").sortable({
    opacity: 0.8,
    cursor: 'move',
    update: function() {
    //Nothing to do
    }
  });
}

//Function to open dialog window for editing a question from preview page
function editSingleQuestion(sid, qid){
  reopen_dialog(850,500, "Edit Question");
  editSingleAssessmentQuestionDialog([sid,qid]);
}

//Function to delete a single question from preview page
function deleteSingleQuestion(sid, qid){
  openConfirmBox(function(){
    $("#alertdialog").dialog("destroy");
		
    //Page loading animation
    $('#dialog').html('<div style="padding-top:190px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

    $.ajax({
      type : "POST",
      url : baseurl+"assessment/actions/delete_question/"+qid,
      data: "status=&validateFrom=&validateTo=",
      async : true,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          reopen_dialog(700, 515, "Preview Question");
          previewAssessmentQuestionsDialog(sid);
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Delete","Do you want to delete this question?");
}

//Function to activate or deactivate an assessment
function activateAssessment(id, status, validateFrom, validateTo){
  if(status=="Active")
    status = "Inactive";
  else
    status = "Active";
		
  //Page loading animation
  $('#dialog').html('<div style="padding-top:50px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
	
  $.ajax({
    type : "POST",
    url : baseurl+"assessment/actions/activate/"+id,
    data: "status="+status+"&validateFrom="+validateFrom+"&validateTo="+validateTo,
    async : true,
    cache : false,
    success : function (msg) {
      if(msg=="Success"){
        reopen_dialog(500, 230, "View Assessment");
        assessmentDetails(id);
        $("#Assess_StatusCode"+id).html('<p>'+status+'</p>');
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to delete an assessment
function deleteAssessment(id, status, validateFrom, validateTo){
  openConfirmBox(function(){
    $("#alertdialog").dialog("destroy");
		
    //Page loading animation
    $('#dialog').html('<div style="padding-top:50px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

    $.ajax({
      type : "POST",
      url : baseurl+"assessment/actions/delete/"+id,
      data: "status="+status+"&validateFrom="+validateFrom+"&validateTo="+validateTo,
      async : true,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          $('#dialog').dialog('destroy');
					
          //code to retain the same page after reloading
          var reduce = parseInt($("#hid_totalRec").val()) - 1;
          var limit = parseInt($("#hid_limit").val());
          var pageno = parseInt($("#hid_pageno").val());
          var mod = reduce % limit;
          if (mod == 0) {
            if (pageno > 1) {
              pageno = pageno - 1;
            }
            else {
              pageno = pageno;
            }
          }
          reloadListingData (10, pageno, "", reduce, baseurl+"assessment", "page");
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Delete","Do you want to delete this Assessment?");
}

//Function to open dialog window for cloning an assessment
function cloneAssessment(id){
  reopen_dialog(600, 335, "Clone Assessment");
  cloneAssessmentDialog(id);
}

//Function to clone an assessment
function cloneAssessmentDialog(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/clone/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-assessment-actdate', 0);
      createDatePicker('edit-assessment-expdate', 1);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });	
}

//Function to go back to assessment preview window from preview question
function goback_assessment(id){
  reopen_dialog(500, 230, "View Assessment");
  cloneAssessmentDialog(id);
}

//Function to open dialog window for reports
function viewReport(id, title){
  reopen_dialog(700, 410, title);
  viewassessmentreport(id);
}

//Function for viewing assessment report
function viewassessmentreport(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/report/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      //Display the returned HTML content
      $('#dialog').html(msg);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to open create assessment page
function createassessmentdialog(){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/edit/0',
    async : true,
    cache : false,
    success : function (msg) {
      //Display the returned HTML content
      $('#dialog').html(msg);
      //formatting date picker
      createDatePicker('edit-assessment-actdate', 0);
      createDatePicker('edit-assessment-expdate', 0);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to display the assessment details
function assessmentDetails(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/details/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      //Display the returned HTML content
      $('#dialog').html(msg);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to edit the assessment details
function editAssessmentDialog(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/edit/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      //Display the returned HTML content
      $('#dialog').html(msg);
      //formatting date picker
      createDatePicker('edit-assessment-actdate', 0);
      createDatePicker('edit-assessment-expdate', 0);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to preview assessment question
function previewAssessmentQuestionsDialog(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/preview/'+id+"/1/30",
    async : true,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to edit assessment question
function editAssessmentQuestionDialog(id){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/question/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);

      $("#edit-question-answer").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      });


      $("#edit-question-answer-value").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      });


      $("#edit-question-insert").click(function(){
        var l = $(this).position().left-1;
        var t = $(this).position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
      $('.ui-dialog').css("filter","");
      //add ck editor to description field
      if(!editor){
        editor = CKEDITOR.replace( 'edit-question-description',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }else{
        if (CKEDITOR.instances['edit-question-description']) {
          CKEDITOR.remove(CKEDITOR.instances['edit-question-description']);
        }
        editor = CKEDITOR.replace( 'edit-question-description',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to edit single assessment question
function editSingleAssessmentQuestionDialog(ids){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/question/'+ids[0]+'/'+ids[1],
    async : true,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);

      $("#edit-question-answer").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      });


      $("#edit-question-answer-value").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      });
			
      $("#edit-question-insert").click(function(){
        var l = $(this).position().left-1;
        var t = $(this).position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
			
      //Function call to reorder
      $(function() {
        $("#reorder ul").sortable({
          opacity: 0.8,
          cursor: 'move',
          update: function() {
            $("#saveorder").show();
          }
        });
      });
      $('.ui-dialog').css("filter","");
      //add ck editor to description field
      if(!editor){
        editor = CKEDITOR.replace( 'edit-question-description',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }else{
        if (CKEDITOR.instances['edit-question-description']) {
          CKEDITOR.remove(CKEDITOR.instances['edit-question-description']);
        }
        editor = CKEDITOR.replace( 'edit-question-description',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to get the filter field data for assessment
function filterdata_assessment () {
  //prepare the field values for filtering
  var search_assessment = $.trim($("#edit-assessment-search-details").val());
  var search_active = $("#edit-assessment-search-active").val();
  var search_expire = $.trim($("#edit-assessment-search-expire").val());
  var search_status = $.trim($("#edit-assessment-search-status").val());
  var data = "&search_assessment="+ encodeURIComponent(search_assessment) +"&search_active="+search_active+"&search_expire="+search_expire+"&search_status="+search_status;
  return data;
}

//Function to export the report
function export_report(assessid, name){
  $('#common-actions').attr('action',baseurl+"assessment/export?id="+assessid+"&name="+name);
  $('#common-actions').submit();
}

//Function to export all data for the report
function export_all_report(){
  $('#common-actions').attr('action',baseurl+"assessment/export?all=all");
  $('#common-actions').submit();
}

//Function to go back to details page from preview question
function backtoDetails(id){
  reopen_dialog(500,230,"View Assessment");
  assessmentDetails(id);
}

//function to reordering subjects
function reorderQuestions (id) {
  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/reorder/list/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);
      //Function call to reorder
      $(function() {
        $("#reorder ul").sortable({
          opacity: 0.8,
          cursor: 'move',
          update: function() {
            $("#saveorder").show();
          }
        });
      });/**/
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save the reordered list
function saveQuestionList (id) {
  var neworder = Array();
  $("#reorder .gridlister").each(function() {
    neworder.push($(this).attr("id").split("_")[1]);
  });
  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    data : "newOrder="+neworder,
    url : baseurl+'assessment/reorder/questions/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      if (msg == "success") {
        reopen_dialog(700,515,"Preview Question");
        previewAssessmentQuestionsDialog(id);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//function to reordering subjects
function reorderAnswers (id) {
  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/reorder/list/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);
      //Function call to reorder
      $(function() {
        $("#reorder ul").sortable({
          opacity: 0.8,
          cursor: 'move',
          update: function() {
            $("#saveorder").show();
          }
        });
      });/**/
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save the reordered list
function saveAnswersList (id) {
  var neworder = Array();
  $("#reorder").each(function() {
    neworder.push($(this).attr("id").split("_")[1]);
  });
  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    data : "newOrder="+neworder,
    url : baseurl+'assessment/reorder/questions/'+id,
    async : true,
    cache : false,
    success : function (msg) {
      if (msg == "success") {
        reopen_dialog(700,515,"Preview Question");
        previewAssessmentQuestionsDialog(id);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to get the list of answers added and reordered
function get_answers(){
  var i=0;
  answers = new Array();
  $("#reorder li").each(function() {
    var obj = $(this).get(0).getElementsByTagName("input")[0];
    var id = obj.value;
    var ans = $(obj).next().html();
    ans_val = ans.substring(ans.lastIndexOf("(")+1,ans.lastIndexOf(")"));
    ans = ans.substring(0,ans.lastIndexOf("("));
    var def = $(obj).next().next().html();
    if(def=="Default"){
      def = true;
    }else{
      def = false;
    }
    answers[i] = [ans_val, ans, id, def];
    i++;
  });
}

//Function to open dialog box
function viewDateWiseReportForm(id, width, height, title){
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#dialog').dialog('destroy');
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-35;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-18)+'px',
    'height':h+'px'
  }).show();

  $('#dialog').html('<div style="padding-top:25px; padding-left:150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  viewDateWiseReport();
}

//Function to show form for selecting date range to view report
function viewDateWiseReport(){
  $.ajax({
    type : "POST",
    url : baseurl+'assessment/datewisereport',
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-date-range-from', -365);
      createDatePicker('edit-date-range-to', -364);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to show report for selected range
function showDateWiseReport(){
  var fromDate = $('#edit-date-range-from').val();
  var toDate   = $('#edit-date-range-to').val();

  var from_Date = new Date(fromDate.replace(/-/g,"/"));
  var to_Date = new Date(toDate.replace(/-/g,"/"));

  var lines = 10;
  var str = "";
  if($.trim(fromDate) == "") {
    str += "Please select Date From";
    lines+=18;
  }
  if($.trim(toDate) == "") {
    if(str!="")
      str+= "<br/>";
    str += "Please select Date To";
    lines+=18;
  }
  if ($.trim(fromDate) != "" && $.trim(toDate) != "") {
    if (to_Date < from_Date) {
      if(str!="")
        str+= "<br/>";
      str += "Date To should be greater than Date From";
      lines+=18;
    }
  }

  if (str != "") {
    resize_dialog(400, 150+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }

  reopen_dialog(700, 400, "Assessment - Date Wise Report");
  $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
	
  $.ajax({
    type : "POST",
    url : baseurl + 'assessment/showdatewisereport',
    data : 'fromDate='+encodeURIComponent(fromDate)+'&toDate='+encodeURIComponent(toDate),
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
	
  return false;
}

//Function to export the datewise report
function export_all_report_datewise(dateFrom, dateTo){
  $('#common-actions').attr('action', baseurl + "assessment/exportdatewisereport?dateFrom=" + dateFrom + "&dateTo=" + dateTo);
  $('#common-actions').submit();
}

//Function to go back the date wise report form 
function goBackToDateWiseReportForm () {
  reopen_dialog(400, 150, 'Assessment - Date Wise Report');
  viewDateWiseReport();
}